package www.sofn.com.contrller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.URLUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import www.sofn.com.constant.Constants;
import www.sofn.com.domain.R;
import www.sofn.com.domain.vo.FilePathVO;
import www.sofn.com.exception.ValidateException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.List;

@Tag(name = "文件上传")
@RestController
@Slf4j
public class FileController {
    @Value("${file.rootPath}")
    private String rootPath;
    private final static String IMG_TYPE = "image";
    @Value("#{'${file.allowImgSuffix}'.split(',')}")
    private List<String> allowImgSuffix;
    @Value("#{'${file.allowVideoSuffix}'.split(',')}")
    private List<String> allowVideoSuffix;
    private final static String VIDEO_TYPE = "video";
    @PostMapping(value = "/img_upload")
    @Operation(summary = "上传图片")
    public R<FilePathVO> imgUpload(@RequestParam(value = "img") MultipartFile file) {
        if (file.isEmpty() || file.getSize() == 0) {
            R.error("图片不能为空");
        }
        String imgName = file.getOriginalFilename();  // 文件名
        String suffixName = file.getContentType();  // 后缀名
        if (!allowImgSuffix.contains(suffixName.toLowerCase())) {
            throw new ValidateException("图片上传失败：系统支持格式为" + allowImgSuffix.toString());
        }
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file.getInputStream());
            bufferedImage.getWidth();
            bufferedImage.getHeight();
        } catch (IOException e) {
            throw new ValidateException("图片上传失败：非法图片");
        }
        String prefix = LocalDate.now().toString();
        imgName = UUID.randomUUID() + "." + suffixName.substring(suffixName.lastIndexOf("/") + 1);
        String imageDir = rootPath + File.separatorChar + prefix + File.separatorChar + IMG_TYPE + File.separatorChar + imgName;
        File tempFile = FileUtil.touch(imageDir);
        FilePathVO filePathVO = null;
        try {
            file.transferTo(tempFile);
            filePathVO = new FilePathVO(imgName, URLUtil.encode(prefix + "/" + IMG_TYPE + "/" + imgName, Charset.forName(Constants.UTF8)));
        } catch (IOException e) {
            log.error("图片上传失败:{}", e.getMessage());
            throw new ValidateException("图片上传失败：系统异常");
        } finally {
            bufferedImage.flush();
        }
        return R.ok(filePathVO);
    }

    @PostMapping(value = "/video_upload")
    @Operation(summary = "上传视频")
    public R<FilePathVO> videoUpload(@RequestParam(value = "video") MultipartFile file){
        if(file.isEmpty()|| file.getSize()==0){
            R.error("视频上传失败：视频大小为0MB");
        }
        String videoName=file.getOriginalFilename();//文件名称
        String suffixName = file.getContentType();  // 后缀名
        if (!allowVideoSuffix.contains(suffixName.toLowerCase())) {
            throw new ValidateException("视频上传失败：系统支持格式为" + allowVideoSuffix.toString() );
        }
        String prefix = LocalDate.now().toString();
        videoName = UUID.randomUUID() + "." + suffixName.substring(suffixName.lastIndexOf("/") + 1);
        String imageDir = rootPath + File.separatorChar + prefix + File.separatorChar + VIDEO_TYPE + File.separatorChar + videoName;
        File tempFile = FileUtil.touch(imageDir);
        FilePathVO filePathVO = null;
        try {
            file.transferTo(tempFile);
            filePathVO = new FilePathVO(videoName, URLUtil.encode(prefix + "/" + VIDEO_TYPE + "/" + videoName, Charset.forName(Constants.UTF8)));
        } catch (IOException e) {
            log.error("视频上传失败:{}", e.getMessage());
            throw new ValidateException("视频上传失败：系统异常");
        } finally {
        }
        return R.ok(filePathVO);

    }
}
